package com.demo.weather.receiver;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.demo.weather.packet.data.FunctionType;

import lombok.AllArgsConstructor;

/**
 * Receiver路由，根据不同功能码选择对应的接收者
 *
 * @author tanheng
 */
@AllArgsConstructor(onConstructor_ = {@Autowired})
@Component
public class ReceiverRouter {

    private Map<FunctionType, PacketReceiver> packetReceiverMap = new ConcurrentHashMap<>();

    private List<PacketReceiver> packetReceivers;

    public PacketReceiver route(FunctionType functionType) {
        PacketReceiver packetReceiver = packetReceiverMap.get(functionType);

        if (packetReceiver == null) {
            for (PacketReceiver item: packetReceivers) {
                if (item.supportedFunctionType() == functionType) {
                    packetReceiverMap.put(functionType, item);
                    return item;
                }
            }
        }

        return packetReceiver;
    }
}